package controllers;

import com.google.gson.annotations.Expose;
import play.exceptions.UnexpectedException;
import play.mvc.Before;
import play.mvc.Controller;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import play.mvc.results.Result;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.GsonBuilder;
import utils.SessionUtils;

/**
 * 一个基础类，方便以后修改
 */
public class SController extends Controller {

    @Before
    static void init() {
        renderArgs.put("_user_", SessionUtils.getCurrentUser());
    }

    protected static void renderJSON(Object o) {
        throw new Result() {
            GsonBuilder gb = new GsonBuilder().addSerializationExclusionStrategy(new ExclusionStrategy() {
                @Override
                public boolean shouldSkipField(FieldAttributes arg0) {
                    Expose annotation = arg0.getAnnotation(Expose.class);
                    return annotation != null && !annotation.serialize();
                }

                @Override
                public boolean shouldSkipClass(Class<?> arg0) {
                    return false;
                }
            });
            String json = gb.create().toJson(o);

            public void apply(Request request, Response response) {
                try {
                    String encoding = getEncoding();
                    setContentTypeIfNotSet(response, "application/json; charset=" + encoding);
                    response.out.write(json.getBytes(encoding));
                } catch (Exception e) {
                    throw new UnexpectedException(e);
                }
            }
        };
    }
}
